package cn.alm.miniodemo.service;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

@Service
public class MinioService {

    @Resource
    private MinioClient minioClient;

    @Value("${minio.endpoint}")
    private String minioEndpoint;

    @Value("${minio.bucket.name}")
    private String minioBucketName;

    public String upload(MultipartFile file) {
        InputStream inputStream;
        String uuid = UUID.randomUUID().toString();
        try {
            inputStream = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder().bucket(minioBucketName).object(uuid + ".jpg").stream(inputStream, inputStream.available(), -1).contentType("image/jpeg").build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String imageUrl = minioEndpoint + "/" + minioBucketName + "/" + uuid + ".jpg";
        return imageUrl;
    }
}
